﻿
/* /////////////////////////////////////////////////////////////////////////////////////////////////
https://www.patreon.com/user?u=33893211

Licensed under CC BY-SA after EarlyAccess ended. (see https://creativecommons.org/licenses/by-sa/4.0/)

///////////////////////////////////////////////////////////////////////////////////////////////// */

using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace PluginIdea
{

    public class UDPReceive : Singleton<UDPReceive>
    {

        public Action<byte[]> MessageRecevdEvent;
        public byte[] dataReveived;

        Thread receiveThread;
        UdpClient client;
        public int port = 8888;
        bool _thread_flag;

        public bool IsAlive
        {
            get
            {
                return _thread_flag;
            }
            set
            {
                _thread_flag = value;
                if (value)
                {
                    receiveThread = new Thread(new ThreadStart(ReceiveData));
                    receiveThread.IsBackground = true;
                    receiveThread.Start();
                    _thread_flag = true;
                }
                else
                {
                    _thread_flag = false;
                    client.Close();
                    receiveThread.Abort();
                    client = null;
                    receiveThread = null;
                }
            }
        }

        private void Awake()
        {
            IsAlive = true;
        }

        private void ReceiveData()
        {
            client = new UdpClient(port);
            while (_thread_flag)
            {
                if (client == null || client.Available < 1)
                {
                    Thread.Sleep(100);
                    continue;
                }

                try
                {
                    IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
                    byte[] data = client.Receive(ref anyIP);

                    if (data.Length > 0)
                    {
                        if (MessageRecevdEvent != null) MessageRecevdEvent(data);
                        lock (this)
                        {
                            this.dataReveived = data;
                        }
                    }

                }
                catch (Exception err)
                {
                    Debug.LogError(err.Message);
                    return;
                }
            }
        }

        private void OnDestroy()
        {
            base.OnDestroy();
            IsAlive = false;
        }
    }
}

